/**
 * 计费管理
 */
var BSTMG = BSTMG || {};
BSTMG.feemanager = {
	$OBJS : {},
	init: function(){
		var that = this;
		/* 初始化选项卡 */
		that.initJqObjs();
		/* 绑定操作 */
		that.bindOperators();
		/* 保存计费模式 */
		that.feeModelOperator();
		/* 绑定计费公司 */
		that.feeModel();
	},
	/* 展示区块，参数为类名 */
	switchArea: function($area,certain){
		for(var key in $area){
			key == certain ? $area[key].show() : $area[key].hide();
		}
	},
	initJqObjs: function(){
		var that = this,
			$objs = that.$OBJS;
		$objs["sec1"] = $("#sec1");
		$objs["sec2"] = $("#sec2");
		$objs["addfeemode"] = $("#addfeemode");
		$objs["feemodel"] = $("#feemodel");
		$objs["modelpanel"] = $("#modelpanel");
		$objs["feemodelname"] = $("#feemodelname");
		$objs["feemodelnote"] = $("#feemodelnote");
		$objs["feetable"] = $("#feetable");
		$objs["feemodelstatus"] = $(".feemodel_status input[name='status']");
		// 选项卡区块
		$objs["switch"] = [];
		$objs["switch"][0] = {
				"sec1": $objs["sec1"],
				"sec2": $objs["sec2"]
		};
	},
	bindOperators: function(){
		
	},
	feeModel: function(){
		var that = this,
			$objs = that.$OBJS ,
			$feemodel = $objs["feemodel"],
			$modelpanel = $objs["modelpanel"];
		$feemodel.on("change",".modelselect",function(){
			var $this = $(this),
				secval = $this.val(),
				secvalue = $.trim( $this.find("option:selected").text() ),
				$jishu = $this.next(".jishu"),
				inpvalue = $.trim( $jishu.val() );
			updateModel( secval , secvalue , inpvalue );
		}).on("input onpropertychange",".jishu",function(){
			var $this = $(this),
				inpvalue = $.trim( $this.val() ),
				$modelselect = $this.prev(".modelselect"),
				secval = $.trim( $modelselect.val() ),
				secvalue = $.trim( $modelselect.find("option:selected").text() );
			if( inpvalue.length > 3 ){
				return false;
			}
			updateModel( secval , secvalue , inpvalue );
		}).on("keypress",".jishu",function(event){
			var $this = $(this),
				inpvalue = $.trim( $this.val() ),
				$modelselect = $this.prev(".modelselect"),
				secval = $.trim( $modelselect.val() ),
				secvalue = $.trim( $modelselect.find("option:selected").text() );
			return (/[\d.]/.test( String.fromCharCode( event.keyCode ) ) );
		});
		// 更新模式文本
		function updateModel( secval , secvalue , inpvalue ){
			if( isNaN( inpvalue ) ) {
				return false;
			};
			var inptxt = inpvalue == "" ? " " : " * " + Number( inpvalue ) ;
			$modelpanel.text( secvalue +  inptxt );
		};
	},
	feeModelOperator: function(){
		var that = this,
			$objs = that.$OBJS ,
			$feetable = $objs["feetable"],
			$thead = $feetable.find("thead"),
			$tbody = $feetable.find("tbody"),
			$feemodel = $objs["feemodel"],
			$modelpanel = $objs["modelpanel"],
			$addfeemode = $objs["addfeemode"],
			$feemodelname = $objs["feemodelname"],
			$feemodelnote = $objs["feemodelnote"],
			$feemodelstatus = $objs["feemodelstatus"];
		var $inpval = $feemodel.find(".jishu") ,
			$secval = $feemodel.find(".modelselect") ;
		var $sec1 = $objs["sec1"] ,
			$operators = $sec1.find(".operator") ;
		// 新增 删除
		$operators.on("click",".addnew",function(){
			feeModelNewLookEdit( null , function(){
				$addfeemode.find(".confirm").removeClass("disabled");
			});
		}).on("click",".delete",function(){
			var $checkbox = $tbody.find("input.simple").filter(":checked");
			if ( $checkbox.length ) {
				var ids = [];
				$checkbox.each(function(index,val){
					var $this = $(this);
					ids.push( $.trim( $this.attr("data-id") ) );
				});
				feeModelDelete( ids );
			}else{
				BSTYUN.dialog.warn("请选择至少一条数据！");
			}
			
		});
		// 全选
		$thead.on("click",".checkall",function(){
			var $this = $(this),
				$current = $this.find(".simple"),
				$parent = $this.parents('table#feetable'),
				$checkbox = $parent.find('input[type=checkbox]').not($current);
			$current.prop("checked") ? $checkbox.prop("checked",true) : $checkbox.prop("checked",false) ;
		});
		$tbody.on("click","input[type=checkbox]",function(){
			var $this = $(this),
				$all = $this.parents("tbody").eq(0).find("input[type=checkbox]"),
				$checkbox = $all.not($this).filter(":checked");
			var $checkall = $thead.find(".checkall input[type=checkbox]");
			($this.prop("checked") && ($checkbox.length + 1) == $all.length ) ? $checkall.prop("checked",true) : $checkall.prop("checked",false) ;
		});
		// 筛选排序
		$thead.on("click",".filter",function(){
			var $this = $(this),
				$dir = $this.next(),
				index = $this.parents("tr").children().index($this.parent()),
				store = [],
				sift = null,
				desc = $dir.hasClass("fa-sort-desc");
			
			$tbody.find('tr').each(function(sub,val){
				var $tr = $(this),
					txt = $tr.find("td").eq(index).text();
				var obj = {
						tr : $tr,
						txt : txt
				}
				store.push(obj);
			});
			if(desc){
				sift = function(a,b){
					/*var x1 = isNaN(a.txt) ? a.txt : Number( a.txt ) ,
						x2 = isNaN(b.txt) ? b.txt : Number( b.txt ) ;*/
					return a.txt > b.txt ? 1 : -1;
				}
				$dir.removeClass("fa-sort-desc").addClass("fa-sort-up");
			}else{
				sift = function(a,b){return a.txt > b.txt ? -1 : 1;} 
				$dir.removeClass("fa-sort-up").addClass("fa-sort-desc");
			}
			$.each( store.sort(sift) , function(){
				$tbody.append(this.tr);
			});
		});
		
		$addfeemode.on("click",".confirm",function(){
			var $this = $(this) ;
			var modename = $.trim( $feemodelname.val() ) ,
				inpval = $.trim( $inpval.val() ), 			
				secval = $.trim( $secval.val() ),
				secvalue = $.trim( $secval.find("option:selected").text() ),
				modelnote = $.trim( $feemodelnote.val() ),
				status = $("input[name='status']:checked").val();
			if( modename == "" ){
				BSTYUN.dialog.warn("计费模式名称不能为空！");
				return  false;
			};
			if( isNaN( inpval ) || inpval == "" ) {
				BSTYUN.dialog.warn("请输入正确的计费基数！");
				return false;
			};
			var id = $this.data("id");
			// ajax请求 保存数据
			$.ajax({
 				url: '/sysAdmin/operate/feeAdmin/saveGoodsFee',
 				type: 'POST',
 				dataType: 'json',
 				data: {
 					id : id ,
 					modename : modename ,
 					secvalue : secvalue ,
 					inpval : inpval ,
 					status: status ,
 					modelnote :modelnote 
 				},
 				beforeSend: function(){},
 				complete: function(){},
 				success: function(data){
 					if(data.isSuccess){
 						BSTYUN.dialog.ok("保存成功！",function(){
 	 						location.href = "/sysAdmin/feeAdmin/feeManager";
 	 					});
 					}else{
 						BSTYUN.dialog.warn("操作失败！请重新保存！");
 					}
 					
 				},
 				error: function(error){
 					BSTYUN.dialog.warn("保存失败！请重新保存！");
 				}
 			});
			that.switchArea($objs["switch"][0],"sec1");
		}).on("click",".cancel",function(){
			that.switchArea($objs["switch"][0],"sec1");
		});
		// 清空表单
		function clearNewFeePanel(){
			$feemodelname.val("");
			$feemodel.find(".jishu").val("");
			$feemodel.find(".modelselect").val("1");
			$feemodelnote.val("");
		};
		// 填充表单
		function fillNewFeePanel( data ){
			$feemodelname.val( data.feeName );
			$feemodel.find(".modelselect").find("option").each(function( index , val ){
				var $this = $(this),
					value = $this.attr("value");
				if( $.trim( $this.text() ) == data.feeFormula ){
					$this.parent().val( value )
					return false;
				};
			});
			$feemodelstatus.filter("[value='" + data.state + "']").prop( "checked" , true );
			$modelpanel.text( data.feeFormula + ' * ' + data.feeBasenum );
			$feemodel.find(".jishu").val( data.feeBasenum );
			$feemodelnote.val( data.remark );
		};
		// 表格操作
		$feetable.on("click",".feemodelook",function(){
			var $this = $(this),
				id = $.trim( $this.parent().parent().find("input.simple").attr("data-id") );
			feeModelNewLookEdit( id , function(){
				$addfeemode.find(".confirm").addClass("disabled");
			});
		}).on("click",".feemodeedit",function(){
			var $this = $(this),
				id = $.trim( $this.parent().parent().find("input.simple").attr("data-id") );
			feeModelNewLookEdit( id , function(){
				$addfeemode.find(".confirm").removeClass("disabled").data("id",id);
			});
		}).on("click",".feemodedelete",function(){
			var $this = $(this),
				id = $.trim( $this.parent().parent().find("input.simple").attr("data-id") );
			feeModelDelete( [id] );
		}).on("click",".feemodestop",function(){
			var $this = $(this),
				id = $.trim( $this.parent().parent().find("input.simple").attr("data-id") ),
				state = 1;
			feeModelToggle( id , state);
		}).on("click",".feemodestart",function(){
			var $this = $(this),
				id = $.trim( $this.parent().parent().find("input.simple").attr("data-id") ),
				state = 0;
			feeModelToggle( id ,state );
		});
		// 查看处理
		function feeModelNewLookEdit( id , callback ){
			clearNewFeePanel();
			that.switchArea($objs["switch"][0],"sec2");
			callback && callback();
			if ( !!!id ){
				return false;
			};
			$.ajax({
 				url: '/sysAdmin/feeAdmin/selectGoodsFeeInfo',
 				type: 'POST',
 				dataType: 'json',
 				data: { id : id },
 				beforeSend: function(){},
 				complete: function(){},
 				success: function(data){
 					if(data.isOk){
 						var modeldata = data.goodsFee ;
 	 					fillNewFeePanel( modeldata );
 					}else{
 						BSTYUN.dialog.warn("查询失败！");
 					}
 					
 				},
 				error: function(error){
 					BSTYUN.dialog.warn("网络原因操作失败！请联系管理员！");
 				}
 			});
		};
		// 删除
		function feeModelDelete( ids ){
			if( !$.isArray(ids) ){
				return false;
			};
			BSTYUN.dialog.confirm("确定要删除选中的数据吗？",function(){
				$.ajax({
	 				url: '/sysAdmin/operate/feeAdmin/deleteByFeeId',
	 				type: 'POST',
	 				dataType: 'json',
	 				data: { ids : ids.join(",") },
	 				beforeSend: function(){},
	 				complete: function(){},
	 				success: function(data){
	 					if(data.isDelete){
	 						BSTYUN.dialog.ok("删除成功！",function(){
		 						location.href = "/sysAdmin/feeAdmin/feeManager";
		 					});
	 					}else{
	 						BSTYUN.dialog.warn("删除失败！请重新删除！<br/>失败原因可能为已有商品使用该计费模式！<br/>请确认该计费模式不在使用中，再进行删除！");
	 					}
	 				},
	 				error: function(error){
	 					BSTYUN.dialog.warn("网络原因操作失败！请联系管理员！");
	 				}
	 			});
			});
		};
		// 停用
		function feeModelToggle( id ,state){
			var str = state == 1 ? "停用" : "启用" ;
			BSTYUN.dialog.confirm("确定要" + str + "吗？",function(){
				$.ajax({
	 				url: '/sysAdmin/operate/feeAdmin/stopByTypeId',
	 				type: 'POST',
	 				dataType: 'json',
	 				data: { 
	 					id : id,
	 					state : state 
	 				},
	 				beforeSend: function(){},
	 				complete: function(){},
	 				success: function(data){
	 					if(data.isStop){
	 						BSTYUN.dialog.ok("设置成功！",function(){
		 						location.href = "/sysAdmin/feeAdmin/feeManager";
		 					});
	 					}else{
	 						BSTYUN.dialog.warn("设置失败！请重新进行该操作！<br/>失败原因可能为已有商品使用该计费模式！<br/>请确认该计费模式不在使用中，再进行设置！");
	 					}
	 				},
	 				error: function(error){
	 					BSTYUN.dialog.warn("网络原因操作失败！请联系管理员！");
	 				}
	 			});
			});
		};
	}
};

$(function(){
	BSTMG.feemanager.init();
});